package com.halfsword.creativecraft.block.custom.machine.blockentity.modules;

import com.halfsword.creativecraft.modules.StagedSteamMechanism;
import com.halfsword.creativecraft.modules.interfaces.IDataSyncFacet;
import com.halfsword.creativecraft.modules.interfaces.IPersistentDataModule;
import com.halfsword.creativecraft.utils.ContainerDataBuilder;
import com.halfsword.creativecraft.utils.ContainerDataReader;
import net.minecraft.core.BlockPos;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState;

/**
 * 蒸汽机制模块实现
 * 负责管理机器的蒸汽机制和能源系统
 */
public class SteamMechanismModule implements IDataSyncFacet, IPersistentDataModule {

    private final String moduleId;
    private final StagedSteamMechanism steamMechanism;
    private boolean isActive = false;
    private boolean dataDirty = false;

    public SteamMechanismModule(String moduleId, double maxTorque, double risingRate, double decliningRate,
                                int waterConsumption, int fuelConsumption, int minWater, int minFuel) {
        this.moduleId = moduleId;
        this.steamMechanism = new StagedSteamMechanism(
                maxTorque, risingRate, decliningRate,
                waterConsumption, fuelConsumption,
                minWater, minFuel
        );
    }

    @Override
    public String getModuleId() {
        return moduleId;
    }

    @Override
    public void tick(Level level, BlockPos pos, BlockState state) {
        steamMechanism.tick();

        // 更新活动状态
        isActive = steamMechanism.getCurrentStage() != StagedSteamMechanism.Stage.IDLE;

        // 如果蒸汽机制数据有变化，标记为脏数据
        if (steamMechanism.isDirty()) {
            markDataDirty();
            steamMechanism.clearDirty();
        }
    }

    @Override
    public void populateContainerData(ContainerDataBuilder builder) {
        // 添加只读字段（客户端只能读取，不能修改）
        builder.addReadOnlyField(() -> (int) (steamMechanism.getCurrentTorque() * 1000))
                .addReadOnlyField(() -> steamMechanism.getCurrentStage().ordinal())
                .addReadOnlyField(steamMechanism::getWaterLevel)
                .addReadOnlyField(steamMechanism::getFuelLevel)
                .addReadOnlyField(() -> isActive ? 1 : 0);
    }

    @Override
    public void readFromContainerData(ContainerDataReader reader) {
        // 客户端数据读取
        double torque = reader.readInt() / 1000.0;
        int stageIndex = reader.readInt();
        int waterLevel = reader.readInt();
        int fuelLevel = reader.readInt();
        boolean active = reader.readInt() != 0;

        // 更新客户端显示
        // 注意：这里只是更新显示，不修改实际数据
        // 实际数据只在服务端修改
    }

    @Override
    public int getDataFieldCount() {
        return 5; // torque, stage, water, fuel, active
    }

    @Override
    public void markDataDirty() {
        dataDirty = true;
    }

    @Override
    public boolean isDataDirty() {
        return dataDirty;
    }

    @Override
    public void clearDataDirty() {
        dataDirty = false;
    }

    /**
     * 获取蒸汽机制实例
     * @return 蒸汽机制实例
     */
    public StagedSteamMechanism getSteamMechanism() {
        return steamMechanism;
    }

    /**
     * 检查蒸汽机制是否处于活动状态
     * @return 是否处于活动状态
     */
    public boolean isActive() {
        return isActive;
    }

    /**
     * 检查是否有足够的蒸汽动力
     * @return 是否有足够的蒸汽动力
     */
    public boolean hasEnoughSteamPower() {
        return steamMechanism.getCurrentStage() == StagedSteamMechanism.Stage.BALANCED &&
                steamMechanism.getCurrentTorque() > steamMechanism.getMaxTorque() * 0.8;
    }

    /**
     * 将模块数据保存到NBT
     * @param tag 要保存到的CompoundTag
     */
    @Override
    public void saveToNBT(CompoundTag tag) {
        CompoundTag steamMechanismTag = new CompoundTag();
        steamMechanism.writeToNBT(steamMechanismTag);
        tag.put("SteamMechanism", steamMechanismTag);
        tag.putBoolean("IsActive", isActive);
    }

    /**
     * 从NBT加载模块数据
     * @param tag 包含数据的CompoundTag
     */
    @Override
    public void loadFromNBT(CompoundTag tag) {
        if (tag.contains("SteamMechanism")) {
            steamMechanism.readFromNBT(tag.getCompound("SteamMechanism"));
        }
        if (tag.contains("IsActive")) {
            isActive = tag.getBoolean("IsActive");
        }
    }

    /**
     * 获取模块数据的唯一标识符
     * @return 模块数据标识符
     */
    @Override
    public String getDataKey() {
        return "steam_mechanism_" + moduleId;
    }

    /**
     * 检查模块数据是否为空
     * @return 数据是否为空
     */
    @Override
    public boolean isEmpty() {
        return steamMechanism.getWaterLevel() == 0 &&
                steamMechanism.getFuelLevel() == 0 &&
                !isActive;
    }

    /**
     * 重置模块数据到默认状态
     */
    @Override
    public void reset() {
        steamMechanism.reset();
        isActive = false;
        markDataDirty();
    }

    /**
     * 添加水
     * @param amount 要添加的水量
     * @return 实际添加的水量
     */
    public int addWater(int amount) {
        int result = steamMechanism.addWater(amount);
        if (result > 0) {
            markDataDirty();
        }
        return result;
    }

    /**
     * 添加燃料
     * @param amount 要添加的燃料量
     * @return 实际添加的燃料量
     */
    public int addFuel(int amount) {
        int result = steamMechanism.addFuel(amount);
        if (result > 0) {
            markDataDirty();
        }
        return result;
    }

    /**
     * 启用系统
     */
    public void enable() {
        steamMechanism.enable();
        markDataDirty();
    }

    /**
     * 禁用系统
     */
    public void disable() {
        steamMechanism.disable();
        markDataDirty();
    }
}